package com.estronger.shopmanage.utils;

import android.app.Activity;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.czt.mp3recorder.MP3Recorder;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class MediaRecordFunc {

	private MP3Recorder recorder;
	private String AUDIO_AMR_FILENAME = "audio.mp3";

	private MediaRecordFunc() {
		if (recorder==null){
			recorder = new MP3Recorder(new File(Environment.getExternalStorageDirectory() + "/Recorder.mp3"));
		}
//		recorder.setHandle(new Handler() {
//			@Override
//			public void handleMessage(Message msg) {
//				switch (msg.what) {
//				case MP3Recorder.MSG_REC_STARTED:
//				case MP3Recorder.MSG_REC_RESTORE:
//					Log.i("MM", "开始录音");
//					break;
//				case MP3Recorder.MSG_REC_STOPPED:
//					Log.i("MM", "停止录音");
//					break;
//				case MP3Recorder.MSG_REC_PAUSE:
//					Log.i("MM", "暂停录音");
//					break;
//				}
//			}
//		});
	}

	private static MediaRecordFunc mInstance;

	public synchronized static MediaRecordFunc getInstance() {
		if (mInstance == null)
			mInstance = new MediaRecordFunc();
		return mInstance;
	}

	public void start(Activity act) {
		// 判断是否有外部存储设备sdcard
		if (isSdcardExit()) {
			// createMediaRecord();
            try {
                recorder.start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
			Toast.show(act, "sdcard不存在", 2000);
			System.out.println("sdcard不存在");
		}
	}

	public void stop() {
		recorder.stop();
	}

	public void pause() {
		if (recorder.isRecording()) {
			recorder.pauseRecord();
		}
	}

	private void createMediaRecord() {

		/* 设置输出文件的路径 */
		String path = getAMRFilePath();
		File file = new File(path);
		if (file.exists()) {
			file.delete();
		} else {
			// 若目录不存在的，先创建目录
			String dir = path.replace(AUDIO_AMR_FILENAME, "");
			file = new File(dir);
			file.mkdirs();
		}
		System.out.println("getAMRFilePath():" + getAMRFilePath());

	}

	/**
	 * 获取AMR格式音频文件路径
	 * 
	 * @return
	 */
	public String getAMRFilePath() {
		String mAudioAMRPath = "";
		if (isSdcardExit()) {
			mAudioAMRPath = Environment.getExternalStorageDirectory()
					+ "/Recorder.mp3";
		}
		return mAudioAMRPath;
	}

	private String createFileName() {
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd_hhmmssSSS",
				Locale.CHINA);
		Date now = new Date();
		String fileName = format.format(now) + ".mp3";
		AUDIO_AMR_FILENAME = fileName;
		return fileName;
	}

	/**
	 * 判断是否有外部存储设备sdcard
	 * 
	 * @return true | false
	 */
	private boolean isSdcardExit() {
		if (Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED))
			return true;
		else
			return false;
	}


}
